<template>
  <div class="flex w-full h-full" style="justify-content: center">
    <div class="w-[300px] h-full overflow-y-auto" v-if="!isShare">
      <McInput />
    </div>
    <div class="flex-1 h-full bg-[#fafbfc] pt-2 dark:bg-[#18181c] overflow-y-auto" v-if="!isShare">
      <mcList />
    </div>
    <div class="w-[300px] h-full overflow-y-auto" v-if="isShare">
      <mcplayer />
    </div>
  </div>
  <NModal v-model:show="showModal" style="width: 90%; max-width: 500px" preset="card" :close-on-esc="false"
    :on-mask-click="() => {
      console.log('on-mask-click');
    }
      ">
    <template #header-extra>
      <div style="font-size: 20px; position: relative; right: 160px">
        扫码登录
      </div>
    </template>
    <div class="flex justify-center" style="padding-top: 10px; background: #dce3e8; border-radius: 8px">
      <iframe style="height: 400px" id="wechatLoginIframe" src="http://suno.phpme.top/api/oauth/render" />
    </div>
  </NModal>
</template>
<script setup lang="ts">
import { NModal } from "naive-ui";
import { setToken } from "@/store/modules/auth/helper";
import McInput from "./mcInput.vue";
import mcList from "./mcList.vue";
import mcplayer from "./mcplayer.vue";
import axios from "axios";
import { useUserStore } from "@/store";
import { useRoute } from "vue-router";
import { computed, ref, watch } from "vue";

const userStore = useUserStore();
const userInfo = computed(() => userStore.userInfo);
watch(userInfo, (val) => {
  showModal.value = val.showModel
})
const showModal = ref<boolean>(!true);
const route = useRoute();
const isShare = ref<boolean>(!!route.query.id);
console.log("🚀 ~ route:", route);

const deleteCode = () => {
  let url = new URL(window.location.href);
  url.searchParams.delete("code");
  url.searchParams.delete("state");
  window.history.replaceState(null, "", url.href);
};

setToken(localStorage.getItem("token") || "");
let url = new URL(window.location.href);
const query = url.search.split("&");
let code = "";
for (const item of query) {
  const [key, value] = item.split("=");
  if (key === "?code") {
    code = value;
  }
}
// 获取code

if (code) {
  axios.post(`/api/oauth/callBackUser`, { code }).then((res) => {
    const {
      data: { data },
    } = res;
    deleteCode();
    localStorage.removeItem("flag");
    localStorage.setItem("token", data.token);
    setToken(data.token);

    userStore.updateUserInfo({
      ...userInfo.value,
      nickname: data.nickname,
      avatar: data.headimgurl,
    });
  });
} else {
  if (!localStorage.getItem("flag")) {
    showModal.value = true;
    localStorage.setItem("flag", "0");
  }
}
</script>
<style scoped>
.n-card-header__close {
  display: none !important;
}
</style>
